
#include "DHD_ObjectManager.h"
#include <algorithm>
using std::sort;

DHD_ObjectManager* DHD_ObjectManager::sm_pInstance = NULL;

DHD_ObjectManager::~DHD_ObjectManager(void)
{
	// Ain't nothing to destruct
}

void DHD_ObjectManager::UpdateObjects(float _fDT)
{

	vector<IBaseInterface*>::iterator iter;
	
	for( iter = m_vObjectList.begin(); iter != m_vObjectList.end();)
	{
		// call each object's update
		// Iterate through the list, iter starts at the beginning
		// Since all our objects will derive from CBase, we can do this
		// across every object.
		(*iter)->Update(_fDT);
		// Increment the iterator, be awesome and do it here and not in the forloop
		iter++;

	}

}
bool ZSort( IBaseInterface* pBaseOne, IBaseInterface* pBaseTwo)
{
	// compare the 2 Y values and sort them 
	return ( pBaseOne->GetPosY() < pBaseTwo->GetPosY() );

}
void DHD_ObjectManager::RenderObjects(void)
{
	sort(m_vObjectList.begin(), m_vObjectList.end(), ZSort);

	for (unsigned int i=0; i < m_vObjectList.size(); i++)
		m_vObjectList[i]->Render();
}

void DHD_ObjectManager::AddObject(IBaseInterface* pObject)
{
	if( pObject == NULL )
		return;

	m_vObjectList.push_back(pObject);

	//	Add my reference to it.
	pObject->AddRef();
}




void DHD_ObjectManager::RemoveObject(IBaseInterface* pObject)
{
	// Check the pointer, don't want garbage <_<
	if( pObject == NULL )
		return;
	// Iterate through the entire list to find that one object we wanna get rid of
	vector<IBaseInterface*>::iterator iter;
	for( iter = m_vObjectList.begin(); iter !=m_vObjectList.end();iter++)
		if((*iter)==pObject)
		{
			// gotcha <3
			(*iter)->Release();

			// Remove the object and WE'RE GOOD YO
			iter = m_vObjectList.erase(iter);
			break;
		}

}

void DHD_ObjectManager::RemoveAllObjects(void)
{
	// Iterate through the entire list and RELEASE ALL THE REFERENCES
	for( unsigned i = 0; i < m_vObjectList.size(); i++ )
	{
		m_vObjectList[i]->Release();
	}
	// then clear it all yo
	m_vObjectList.clear();
}

void DHD_ObjectManager::CheckCollisions()
{
	for (unsigned int i = 0; i < m_vObjectList.size(); i++)
	{
		for (unsigned int j = 0; j < m_vObjectList.size(); j++)
		{
			if (m_vObjectList[i]->GetType() == m_vObjectList[j]->GetType())
				continue;
			if (m_vObjectList[i]->CheckCollision(m_vObjectList[j]))
				break;
		}
	}
}
